
// 来源 https://fly.layui.com/extend/treeSelect/
layui.define('tree', function (exports) {
    "use strict";

    var _MOD = 'treeSelect',
        treeData = {}, //全局树形数据缓存
        $ = layui.jquery,
        win = $(window),
        TreeSelect = function () {
            this.v = '1.0.0';
            this.datas = [];
        };
    // 函数防抖
    function debounce(fun, delay) {
        return function (args) {
            var that = this
            var _args = args
            clearTimeout(fun.id)
            fun.id = setTimeout(function () {
                fun.call(that, _args)
            }, delay)
        }
    }

    /**
     * 初始化下拉树选择框
     */
    TreeSelect.prototype.render = function (options) {
        var _this = this;
        console.log(options);
            // elem
        var elem = options.elem,
            // 请求地址
            data = options.data,
            // ajax请求方式：post/get
            type = options.type,
            // 节点点击回调
            click = options.click,
            // key.id: id对应的字段, key.pid: pid对应的字段, key.rootPid: 根节点的pid数值
            key = options.key,
            search = options.search || false,
            tmp = new Date().getTime(),
            treeDiv = '#treeSelect-div-'+ tmp,
            treeInputId = 'treeSelect-input-' + tmp;

        var init = {
            tree: function () {
                $.ajax({
                    url: data,
                    type: type,
                    dataType: 'json',
                    success: function (d) {
                        _this.datas = d;
                        treeData = d;
                        layui.tree({
                            elem: '#treeSelect-ul-' + tmp,
                            nodes: d
                        });
                        // 原有结构的东西被删除了
                        init.removeLayTree();
                        init.setIndex(d, $(elem).next(), true);
                    }
                });
                return init;
            },
            removeLayTree: function () {
                $(elem).next().find('ul.layui-tree').remove();
            },
            setIndex: function (data, parentDom, isRoot) {
                var d = data;
                // 生成新的tree以便支持lay-index
                var tree = $('<ul>').addClass('layui-anim layui-anim-upbit tree-list-ul');
                if (isRoot) {
                    tree.attr({
                        'id': 'treeSelect-ul-' + tmp
                    }).addClass('layui-tree layui-box');
                }
                for (var i = 0; i < d.length; i++) {
                    var obj = d[i];
                    var iSpread = '<i class="layui-icon layui-icon-triangle-r"></i>';
                    // 没有子节点，不需要图标
                    if (obj.children == null || obj.children.length == 0) iSpread = '';
                    var crObj = {}
                    crObj.id = d[i].id;
                    crObj.name = d[i].name;
                    crObj.pid = d[i].pid;
                    var setData = JSON.stringify(crObj);

                    var a = $('<a setd='+ setData +'>');
                    var iBranch = '<i class="layui-icon layui-icon-file"></i>';
                    // 如果是根节点，不需要图标
                    if (isRoot)  iBranch = '';
                    var cite = $('<cite>').html(obj.name);
                    // 获取主键名称
                    var id;
                    if (key != null && key.id != null){
                        id = obj[key.id];
                    } else {
                        id = obj.id;
                    }
                    // 危险项
                    var li = $('<li class="tree-list-li">').attr('lay-index', id).append(iSpread).append(a.append(iBranch).append(cite));
                    if (obj.children != null && obj.children.length > 0){
                        init.setIndex(obj.children, li, false);
                    }
                    tree.append(li);
                }
                parentDom.append(tree);
            },
            input: function () {
                $(elem).hide();
                var $treeDiv = $('<div>').attr({
                            id: 'treeSelect-div-'+ tmp
                        }).addClass('layui-treeselect layui-unselect layui-form-select'),
                    placeholder = $(elem).attr('placeholder'),
                    $treeTitle = $('<div class="layui-select-title">').attr('id', 'treeSelect-title-' + tmp),
                    value = $(elem).val(),
                    $treeInput = $('<input>').attr({
                        placeholder: placeholder,
                        readonly: !search,
                        type: 'text',
                        value: value,
                        id: treeInputId,
                    }).addClass('layui-input layui-unselect').click(function () { }),
                    $treeUl = $('<ul>').addClass('layui-anim layui-anim-upbit layui-tree layui-box').attr({
                            id: 'treeSelect-ul-' + tmp,
                        });
                $(elem).after($treeDiv.append($treeTitle.append($treeInput).append('<i class="layui-edge"></i>')).append($treeUl));
                init.tree().titleToggle().spreadToggle().select();

                return init;
            },
            style: function () {
                var style = '<style>' +
                    '.layui-treeselect .layui-tree{' +
                    '   display: none;\
                        position: absolute;\
                        left: 0;\
                        top: 42px;\
                        padding: 5px 0;\
                        z-index: 999;\
                        min-width: 100%;\
                        border: 1px solid #d2d2d2;\
                        max-height: 300px;\
                        overflow-y: auto;\
                        background-color: #fff;\
                        border-radius: 2px;\
                        box-shadow: 0 2px 4px rgba(0,0,0,.12);\
                        box-sizing: border-box;' +
                    '}' +
                    '.layui-tree-branch{display: none;}' +
                    '.layui-treeselect .layui-tree li>i.layui-icon{cursor: pointer;}' +
                    '.layui-form-selected .layui-tree{display: inline-block}</style>'
                $('head').append(style);
            },
            titleToggle: function () {
                init.event('click', '#treeSelect-title-' + tmp, function () {
                    var $treeUl = $(this).closest('.layui-treeselect');
                    if ($treeUl.hasClass('layui-form-selected')) {
                        $treeUl.removeClass('layui-form-selected').addClass('layui-unselect');
                    } else {
                        $treeUl.addClass('layui-form-selected').removeClass('layui-unselect');
                    }
                });
                return init;
            },
            spreadToggle: function () {
                var dom = treeDiv + ' ' + '.layui-tree li>i.layui-icon';
                init.event('click', dom, function () {
                    var ul = $(this).parent().find('ul').eq(0),
                        down = 'layui-icon-triangle-d',
                        right = 'layui-icon-triangle-r';
                    if (!ul.hasClass('layui-show')){
                        ul.addClass('layui-show');
                        $(this).addClass(down).removeClass(right);
                    } else {
                        ul.removeClass('layui-show');
                        $(this).addClass(right).removeClass(down);
                    }
                    return false
                });
                return init;
            },
            // searchDom: function(val){
            //     var datas = $.extend([], treeData)
            //     var eee = deepQuery(datas, val)
            //     console.log('eee', eee);

            // },
            deepQuery(tree,pid) {
                var isGet = false;
                var retNode = null;
                var pids = [];
                function deepSearch(tree,id){
                    for(var i = 0; i<tree.length; i++) {
                        if(tree[i].children && tree[i].children.length>0) {
                            deepSearch(tree[i].children, pid);
                        }
                        if(pid === tree[i].id) {
                            isGet || (retNode = tree[i]);
                            isGet = true;

                            pids.push(tree[i].id)
                            break;
                        }
                    }
                }
                deepSearch(tree,pid);
                return retNode;
            },
            // 找到符合条件的元素
            searchName: function(name){
                var isGet = false;
                var retNode = null;
                var result = [];

                var tree = $.extend([], _this.datas)
                function deepSearch(tree, name){
                    for(var i = 0; i<tree.length; i++) {
                        if(tree[i].children && tree[i].children.length>0) {
                            deepSearch(tree[i].children, name);
                        }
                        if(tree[i].name.search(name) != -1) {
                            result.push(tree[i].id);
                        }
                    }
                }
                deepSearch(tree, name);
                console.log('通过名字找到符合条件', result)
                return result;
            },
            // 找到符合条件的dom li
            filterDom: function(ids){
                var dom = treeDiv + ' ' + 'ul li';
                var res = [];
                $(dom).each(function(index, item){
                    var id = $(item).attr('lay-index');

                    for (var i = ids.length - 1; i >= 0; i--) {
                        if (ids[i] == id) {
                            res.push(item)
                        }
                    }
                });
                console.log('返回符合条件的dom', res);
                return res;
            },
            // 给符合条件的dom的上下级环境进行处理
            markDom: function(doms){
                $(treeDiv).find('li.tree-list-li').hide();
                // console.log('doms', $(doms[0]).parents('li.tree-list-li'));
                for (var i = doms.length - 1; i >= 0; i--) {
                    // 本身也要现实
                    $(doms[i]).parents('li.tree-list-li').css('display', 'block');
                    $(doms[i]).parents('ul.tree-list-ul').addClass('layui-show');
                    $(doms[i]).css('display', 'block');
                    $(doms[i]).parents('li.tree-list-li').children('.layui-icon').removeClass('layui-icon-triangle-r').addClass('layui-icon-triangle-d');
                    // ul.addClass('layui-show')
                }
                // 首个ul 不在观察列表
                $(treeDiv).children('ul').removeClass('layui-show');
            },
            search: function() {
                var debounceAjax = debounce(init.initSearch, 500);
                $('#' + treeInputId).unbind('input propertychange').bind('input propertychange', function(e){

                    // 显示效果
                    $(treeDiv).addClass('layui-form-selected');
                    var val = $(this).val();
                    debounceAjax(val);
                });
            },
            initSearch: function(val){
                var getNodesID = init.searchName(val);
                var getDom = init.filterDom(getNodesID);
                init.markDom(getDom)
            },
            select: function () {
                var dom = treeDiv + ' ' + 'ul li a';
                init.event('click', dom, function () {
                    // 如果有子类节点就展开
                    if ($(this).prev('i').size() > 0) {
                        $(this).prev('i').trigger('click');
                    }

                    var cite = $(this).find('cite').html();
                    var target = $(this).closest('.layui-tree').attr('id');
                    var reg = target.replace(/[^0-9.]/g, '');
                    var div = $(this).closest('.layui-treeselect');
                    $('#treeSelect-input-' + reg).val(cite);
                    // $('#' + treeInputId).val(cite);
                    $(elem).attr('value', $(this).parent().attr('lay-index'));
                    // div.removeClass('layui-form-selected').addClass('layui-unselect');
                    var atr = $(this).attr('setd');
                    if (typeof atr != 'string') {
                        layer.msg('程序报错');
                        console.error('程序报错');
                        return;
                    }
                    click && click(JSON.parse(atr));

                    return false;
                    
                    // if (click) {
                    //     // 获取当前节点
                    //     var getThisNode = function(datas) {
                    //         var node = {};
                    //         for (var i = 0; i < datas.length; i++) {
                    //             var data = datas[i],
                    //                 name = data.name,
                    //                 href = data.href;
                    //             if (name === cite){
                    //                 node = data;
                    //                 break;
                    //             }

                    //             for (var j = 0; j < data.children.length; j++) {
                    //                 var child = data.children[j],
                    //                     cName = child.name;
                    //                 if (cName === cite) {
                    //                     node = child;
                    //                     break;
                    //                 }
                    //             }
                                
                    //         }
                    //         return node;
                    //     };
                        
                    //     click(getThisNode(treeData));
                    // }
                });
                return init;
            },
            event: function (evt, elem, func) {
                $('body').off(evt, elem).on(evt, elem, func);
            }
        };
        init.input().style();
        if (search) {
            console.log('search')
            init.search()
        }
        return new TreeSelect();
    };

    /**
     * 设置提示文字
     * @param filter lay-filter属性
     * @param title 需要显示的提示内容
     * @returns {TreeSelect}
     */
    TreeSelect.prototype.setTitle = function (filter, title) {
        $('*[lay-filter='+ filter +']').next().find('input').attr('placeholder', title);
        return new TreeSelect();
    };

    /**
     * 选中节点
     * @param filter lay-filter属性
     * @param id 选中的id
     */
    TreeSelect.prototype.checkNode = function (filter, id) {
        var o = $('*[lay-filter='+ filter +']'),
            ts = o.next(),
            tsInput = ts.find('input'),
            li = ts.find('ul.layui-tree li[lay-index]');
        li.each(function (i, el) {
            var index = $(el).attr('lay-index');
            if (index == id) {
                var title = $(el).find('cite').eq(0).text();
                tsInput.val(title);
                o.val(index);
                return false;
            }
        })
    };


    var treeSelect22 = {
      //分页渲染
      render: function(options){
        var o = new TreeSelect();
        o.render(options)
        // return o;
      }
    }


    // var treeSelect = new TreeSelect();
    //暴露接口
    exports(_MOD, treeSelect22);
})